const express = require("express");
const app = express();
const router = require("./router");
const bodyParser = require("body-parser");
const { swaggerUi, specs, swaggerOptions } = require('./swagger');
const cors = require("cors")

// 配置CORS，允许前端访问
app.use(cors({
    origin: ['http://localhost:5173', 'http://127.0.0.1:5173'], // 允许Vite开发服务器的域名
    credentials: true, // 允许携带凭证
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // 允许的HTTP方法
    allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'] // 允许的请求头
}))
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json()); // 添加JSON解析支持
app.use(express.static('public'));

// Swagger 文档路由
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs, {
    explorer: true,
    customCss: '.swagger-ui .topbar { display: none }',
    customSiteTitle: "指间联盟 API 文档",
    swaggerOptions: {
        ...swaggerOptions,
        filter: true,
        showRequestHeaders: true,
        tryItOutEnabled: true
    }
}));

app.use("/api",router);

const server = app.listen(3000,() =>{
    console.log(`服务器运行在3000端口上`);
    console.log(`API 文档地址: http://localhost:3000/api-docs`);
})